/*
 * Copyright 2006 Berry Crawford
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.judo.utility.scripts;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.judo.generate.mvc.MVCGenerator;
import org.judo.utility.FileDataReader;
import org.judo.utility.SystemInReader;

public class UndoMVCScript
{
	public static void undo()
	{
		try
		{
			String last = FileDataReader.getFileData("/saved/last.txt");
			String files[] = last.split("00000");
			
			System.out.println("This command will delete all these files:");
			
			System.out.println();
			
			for (String file:files)
			{
				if (file.trim().equals(""))
					continue;
				
				System.out.println(file);
			}
			
			System.out.println();
			
			System.out.print("Are you sure you want to delete all these files?(Y/N): ");
			String answer = SystemInReader.getUserInput();			
			
			System.out.println();
			
			if (answer.equals("Y") || answer.equals("y"))
			{
				for (String file:files)
				{
					file = file.trim();
					
					if (file.equals(""))
						continue;
					
					File delFile = new File(file);
					
					if (delFile.delete())
						System.out.println("Deleted: "+file);
					else
						System.out.println("Could not delete: "+file);
				}

				System.out.println();
				writeFile(new File("./script/saved/last.txt"),"");
				System.out.print("Files Deleted.  Refresh IDE to see changes.  Press Enter");
				SystemInReader.getUserInput();
			}
			else
			{
				System.out.println();
				System.out.print("No Change to files.  Press Enter");
				SystemInReader.getUserInput();
			}
			
			
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Could not execute script: "+e);
			System.out.print("Press Enter to continue...");
			SystemInReader.getUserInput();
		}
	}
	
	protected static void writeFile(File file,String text)
	{
		FileWriter writer = null;
		
		try
		{
			writer = new FileWriter(file);
			writer.write(text);
			
			if (!file.getName().equals("last.txt"))
				System.out.println("File created: "+file.getName());
		} 
		catch (Exception e)
		{
			System.out.println("Error creating File: "+file.getName()+":"+e);
			e.printStackTrace();
			return;
		}
		finally
		{
			try{writer.close();}catch(Exception e){}
		}
	}
}
